import {
  login,
  getInfo
} from '@/api/other'
import {
  getToken,
  setToken,
  removeToken
} from '@/utils/auth'
// import {
//   Base64
// } from 'js-base64'

const user = {
  state: {
    token: getToken(),
    name: '',
    avatar: '',
    department: '',
    userId: '',
    roles: [],
    rolesId: ''
  },

  mutations: {
    SET_TOKEN: (state, token) => {
      state.token = token
    },
    SET_NAME: (state, name) => {
      state.name = name
    },
    SET_AVATAR: (state, avatar) => {
      state.avatar = avatar
    },
    SET_DEPARTMENT: (state, department) => {
      state.department = department
    },
    SET_USERID: (state, userId) => {
      state.userId = userId
    },
    SET_ROLES: (state, roles) => {
      state.roles = roles
    },
    SET_ROLEID: (state, rolesId) => {
      state.rolesId = rolesId
    }
  },

  actions: {
    // 登录
    Login({
      commit
    }, userInfo) {
      const userId = userInfo.userId.trim()
      return new Promise((resolve, reject) => {
        login(userId, userInfo.passWord).then(response => {
          const data = response.data
          let baseToken = data.token;
          setToken(baseToken)
          commit('SET_TOKEN', baseToken)
          resolve()
        }).catch(error => {
          reject(error)
        })
      })
    },

    // 获取用户信息
    GetInfo({
      commit,
      state
    }) {
      return new Promise((resolve, reject) => {
        getInfo().then(response => {
          const data = response.data
          if (data.roleCatalog && data.roleCatalog.length > 0) { // 验证返回的roles是否是一个非空数组['admin','edtor']
            commit('SET_ROLES', data.roleCatalog)
          } else {
            reject('getInfo: roles must be a non-null array !')
          }
          commit('SET_NAME', data.name)
          commit('SET_DEPARTMENT', data.department)
          commit('SET_USERID', data.userId)
          commit('SET_ROLEID', data.roleId)
          // commit('SET_AVATAR', data.avatar)
          resolve(response)
        }).catch(error => {
          reject(error)
        })
      })
    },

    // 登出
    LogOut({
      commit,
      state
    }) {
      return new Promise((resolve, reject) => {
        logout(state.token).then(() => {
          commit('SET_TOKEN', '')
          commit('SET_ROLES', [])
          removeToken()
          resolve()
        }).catch(error => {
          reject(error)
        })
      })
    },

    // 前端 登出
    FedLogOut({
      commit
    }) {
      return new Promise(resolve => {
        commit('SET_TOKEN', '')
        removeToken()
        resolve()
      })
    }
  }
}

export default user